<template>
  <div id="qcReportDiv">
    <Breadcrumb content="质控月报表" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="16">
          <vxe-form :data="searchForm" class-name="padding-sm width-100-percentage" title-width="80px">
            <vxe-form-item title="仪器" :item-render="{}" field="instrId" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-select v-model="data.instrId" :filterable="true" clearable @change="valueChangeEvent">
                  <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
                </vxe-select>
              </template>
            </vxe-form-item>
            <vxe-form-item title="质控月份" :item-render="{}" field="qcDate" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.qcDate" placeholder="选择月份" type="month" valueFormat="yyyy-MM-dd" transfer></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="质控编号" :item-render="{}" field="qcNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.qcNo" placeholder="质控编号" type="text" clearable></vxe-input>
              </template>
            </vxe-form-item>
            <vxe-form-item title="次数" :item-render="{}" field="qcNum" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-select v-model="data.qcNum" :filterable="true" clearable>
                  <vxe-option v-for="qcSeq in qcSeqList" :key="qcSeq.code" :value="qcSeq.code" :label="qcSeq.name"></vxe-option>
                </vxe-select>
              </template>
            </vxe-form-item>

            <vxe-form-item title="项目" :item-render="{}" field="qcItemId" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-select v-model="data.qcItemId" :filterable="true" clearable>
                  <vxe-option v-for="qcItem in qcItemList" :key="qcItem.id" :value="qcItem.id" :label="qcItem.itemDictName + '(' + qcItem.itemDictCode + ')'"></vxe-option>
                </vxe-select>
              </template>
            </vxe-form-item>

          </vxe-form>
        </Pane>
        <Pane size="84">
          <el-scrollbar style="height: 100%">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="qloading" :disabled="disabledTag" @click="findQcMaterialMonthData"></vxe-button>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-download" content="导出" :loading="qloading" :disabled="disabledTag" @click="exportExcel"></vxe-button>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-print" content="打印" :loading="isPrintting" :disabled="disabledTag" @click="quietPrint('printBarcodeMZTable')"></vxe-button>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-file-pdf" content="预览" :loading="isPrintting" :disabled="disabledTag" @click="previewPrint()"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="iqcOut-main">
              <el-row>
                <el-col :span="24" style="text-align: center; font-size: 18px">
                  <p>室内质控月报表</p>
                </el-col>
                <el-col :span="6">{{ qcMaterialInfo.qcMonthName  }}</el-col>
                <el-col :span="6">质控批号：{{ qcMaterialInfo.batchNum  }}</el-col>
                <el-col :span="6" :offset="6">仪器：{{ qcMaterialInfo.instrName }}</el-col>
              </el-row>
              <div class="tableBox">
                <vxe-table ref="tabRef1" class="mytable-scrollbar" height="700" v-loading="mloading" border align="center" :data="qcMaterialInfo.qcMaterialRsultList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
                  <vxe-column field="itemDictName" title="项目名称"></vxe-column>
                  <vxe-colgroup title="质控靶值设定">
                    <vxe-column field="targetMean" title="均值" width="100"></vxe-column>
                    <vxe-column field="targetSd" title="SD" width="100"></vxe-column>
                    <vxe-column field="targetCv" title="CV%" width="100"></vxe-column>
                  </vxe-colgroup>
                  <vxe-colgroup title="当月测定结果">
                    <vxe-column field="resultMean" title="均值" width="100">
                      <template #default="{ row }">
                        <span>{{ row.resultMean }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="resultSd" title="SD" width="100">
                      <template #default="{ row }">
                        <span>{{ row.resultSd }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="resultCv" title="CV%" width="100">
                      <template #default="{ row }">
                        <span>{{ row.resultCv }}</span>
                      </template>
                    </vxe-column>
                    <vxe-column field="resultCnt" title="N" width="100"></vxe-column>
                    <vxe-column field="resultOutCnt" title="失控数" width="100"></vxe-column>
                    <vxe-column field="resultInCnt" title="在控率" width="100">
                      <template #default="{ row }">
                        <span>{{ row.resultInCnt}}</span>
                      </template>
                    </vxe-column>
                  </vxe-colgroup>
                </vxe-table>
              </div>
              <el-row>
                <el-col :span="24">质控总结：{{ qcMaterialInfo.summary  }}</el-col>
              </el-row>
            </div>
          </el-scrollbar>
        </Pane>
      </Splitpanes>
    </div>
    <MultiRptPreview :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'报告预览'" />
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
import { DateToString, formatDateTime, getAssetsFile } from '@/utils/common';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import MultiRptPreview from '@/components/MultiRptPreviewZdy.vue';
import { AppStore } from '@/stores/store';
import QuietPrint from '@/components/QuietPrint.vue';

let store = AppStore();

import axios from 'axios';
let disabledTag = ref(false);
let qloading = ref(false);
let searchForm = reactive({
  instrId: '',
  qcDate: DateToString(new Date()),
  qcNo: '',
  qcNum: 'avg',
  qcItemId: ''
});
let qcMaterialInfo = reactive({
  qcMonthName: '',
  instrName: '',
  batchNum: '',
  summary: '',
  qcMaterialRsultList: []
}) as any;
let instrList: any = reactive([]); //左侧仪器下拉项
let qcItemList: any = reactive([]);
let qcSeqList: any = reactive([
  {
    code: 'avg',
    name: '均值'
  },
  {
    code: 'best',
    name: '最好1次'
  },
  {
    code: '1',
    name: '第1次'
  },
  {
    code: '2',
    name: '第2次'
  },
  {
    code: '3',
    name: '第3次'
  }
]);

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findInstrSetupList();
});
// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      instrList.push(...res.data);
      if (instrList.length > 0) {
        searchForm.instrId = instrList[0].id;
        findQcInstrItemList();
      }
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

function findQcInstrItemList() {
  if (IsEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    qcItemList.length = 0; //放入数据前清空数据
    const url = '/api/qc/qcInstrItem/findQcInstrItemList';
    proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: { pid: searchForm.instrId }
      })
      .then((res: any) => {
        qcItemList.push(...res.data);
      })
      .catch((err: any) => {
        console.log(err);

        VxeMessage('获取右侧获取质控项目表格数据异常2', VxeNotifyType.error);
      });
  }
}

function findQcMaterialMonthData() {
  if (IsEmpty(searchForm.qcNo)) {
    VxeMessage('请输入质控编号', VxeNotifyType.error);
    return;
  }
  if (IsEmpty(searchForm.instrId)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
    return;
  }
  qloading.value = true;
  qcMaterialInfo.qcMaterialRsultList.length = 0;

  const url = '/api/qc/qcMaterialItemResult/findQcMaterialMonthData';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        instrId: searchForm.instrId,
        qcMonth: formatDateTime(new Date(searchForm.qcDate), 'yyyy-MM'),
        qcNo: searchForm.qcNo,
        qcNum: searchForm.qcNum,
        qcItemId: searchForm.qcItemId
      }
    })
    .then((res: any) => {
      if (res.data.qcMaterial) {
        qcMaterialInfo.instrName = res.data.qcMaterial.instrName;
        qcMaterialInfo.qcMonthName = res.data.qcMaterial.qcMonthName;
        qcMaterialInfo.batchNum = res.data.qcMaterial.batchNum;
      }

      if (res.data.qcMaterialSummary) {
        qcMaterialInfo.summary = res.data.qcMaterialSummary.summary;
      }
      if (res.data.qcMaterialRsultList) {
        qcMaterialInfo.qcMaterialRsultList.push(...res.data.qcMaterialRsultList);
      }
      qloading.value = false;
    })
    .catch((err: any) => {
      qloading.value = false;
      console.log(err);
      VxeMessage('获取右侧质控项目表格数据异常1', VxeNotifyType.error);
    });
}

function exportExcel() {
  axios
    .post(
      (window as any).apiUrl.VITE_SERVER_URL + '/api/qc/qcMaterialItemResult/exportExcel',
      { qcMonthName: qcMaterialInfo.qcMonthName, data: qcMaterialInfo.qcMaterialRsultList, batchNum: qcMaterialInfo.batchNum, instrName: qcMaterialInfo.instrName, summary: qcMaterialInfo.summary },
      {
        responseType: 'blob'
      }
    )
    .then((res: any) => {
      //const blob = new Blob([JSON.stringify(data)], ...)
      const blob = new Blob([res.data], {});
      let dom = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      dom.href = url;
      dom.download = decodeURI('质控月报表.xlsx');
      dom.style.display = 'none';
      document.body.appendChild(dom);
      dom.click();
      dom.parentNode.removeChild(dom);
      window.URL.revokeObjectURL(url);
    })
    .catch((err) => {
      console.log('异常', err);
    });
}

const isPreviewRpt = ref(false);
let reportList = reactive([]);

function previewPrint() {
  isPreviewRpt.value = false;
  reportList.length = 0;
  const inputDate = formatDateTime(new Date(searchForm.qcDate), 'yyyy-MM'); // 输入示例
  const dateObj = moment(inputDate, 'YYYYMM'); // 解析输入年月‌:ml-citation{ref="4" data="citationList"}
  // 当月第一天
  const firstDay = dateObj.startOf('month').format('YYYY-MM-DD');
  // 当月最后一天
  const lastDay = dateObj.endOf('month').format('YYYY-MM-DD');
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;

      const data = {
        instrId: searchForm.instrId,
        qcMonth: formatDateTime(new Date(searchForm.qcDate), 'yyyy-MM'),
        qcNo: searchForm.qcNo,
        qCDateS: firstDay + ' 00:00:00.0',
        qCDateE: lastDay + ' 23:59:59.99',
        qcNum: searchForm.qcNum,
        qcItemId: searchForm.qcItemId,
        orgId: store.userInfo.orgId,
        reportId: reportId,
        reportTemplateName: '月指控报表'
      };
      reportList.push(data);
      console.log(reportList);

      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

let printParamsObj = ref(null);

function quietPrint() {
  const inputDate = formatDateTime(new Date(searchForm.qcDate), 'yyyy-MM'); // 输入示例
  const dateObj = moment(inputDate, 'YYYYMM'); // 解析输入年月‌:ml-citation{ref="4" data="citationList"}
  // 当月第一天
  const firstDay = dateObj.startOf('month').format('YYYY-MM-DD');
  // 当月最后一天
  const lastDay = dateObj.endOf('month').format('YYYY-MM-DD');
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
    .get(url, { params: { url: '/' + proxy.$route.name } })
    .then((res: any) => {
      const reportId = res.data;
      const candom: any = document.getElementById('qcEchart');
      let arr = [];
      arr.push({
        ReportName: reportId,
        ReportParameters: [
          { Name: 'instrId', Value: searchForm.instrId },
          { Name: 'qcMonth', Value: formatDateTime(new Date(searchForm.qcDate), 'yyyy-MM') },
          { Name: 'qcNo', Value: searchForm.qcNo },
          { Name: 'qcNum', Value: searchForm.qcNum },
          { Name: 'qCDateS', Value: firstDay + ' 00:00:00.0' },
          { Name: 'qCDateE', Value: lastDay + ' 23:59:59.99' },
          { Name: 'qcItemId', Value: searchForm.qcItemId },
          { Name: 'orgId', Value: store.userInfo.orgId }
        ],
        PdfPrinterSetting: { PdfPrinterCopies: 1 }
      });
      printParamsObj.value = arr;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function valueChangeEvent() {
  findQcInstrItemList();
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}
</script>

<style lang="scss" scoped>
#qcReportDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      .iqcOut-main {
        margin-left: 50px;
        width: 70%;
        height: calc(100%);
      }
    }
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    //右侧质控项目表格
    .tableBox {
      height: calc(100%);
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;

      .dialog-footer {
        height: 40px;
      }
    }
  }
}
</style>